import React from 'react';
import { Button, Icon, message } from 'antd';
import classnames from 'classnames'
import ClientContent from './clientContent';
import MatterContent from './matterContent';
import NewMatter from './newMatter';
import { string } from 'prop-types';
const ClientAndMattersName = ({
  vedioList, isEditMatter, memoText, isEditBatch, infoId, getFileLists, currentFile,
  getTagList, memoList,
  goBackToIndex,
  showClient,
  clientList,
  onChangeClientLsit,
  paginationClientList,
  selectedRowKeysClient,
  getClientCurrentLists,
  // AllClientList,
  orgListData,
  onChangeMatterPages,
  paginationMatter,
  showFinalMatter,
  getCopiesToindex,
  number,
  saveMatterDataToIndex,
  matter,
  matterIndex,
  name,
  goToclientAndMatterView,
  goToNewMatterView,
  getORGCurrentLists,
  selectedRowKeysORG,
  clientRowKeys,
  ORGRows,
  toShowAddViews,
  showAddView,
  getPartyClientArrys,
  PartyClientKeys,
  PartyClientList,
  getPartyORGArrys,
  PartyORGKeys,
  PartyORGList,
  reSetAddParTyData,
  confirmToClientAndmatterNames,
  partyList,
  PartyClientKeysCancle,
  PartyORGKeysCancle,
  choiceMatterToclientAndMatterViews,
  choiceClientFuction,
  choiceMatterFuction,
  saveDataToIndex,
  heelPartyLists,
  getVedioLists,
  reserMatter,
  deleteMatterItemToClientAndMatters,
  supplementState,
  matterOtherData,translation,currency,
  editMatterToClientAndMatters, showCascader, matterId, fileList, changeSupplementStates,dispatch
}) => {
  const goToBack = () => {
    goBackToIndex();
  };
  const saveData = () => {
    let timestamp = new Date().getTime()
    let party = [];
    let finalData = {};
    let partyName = []
    let partyMobile = []
    // finalData.localId = Date.parse(new Date());
    finalData.localId = sessionStorage.getItem("batchId");
    const infoChecked = sessionStorage.getItem("infoChecked")
  
    matter.map((item) => {
      if (infoChecked) {
        item.infoId = parseInt(infoChecked);
      }
      delete item['index'];
      delete item['files'];
    })
    // console.log(matter, matter)
    finalData.supplement = JSON.stringify({
      // "1":{
      //     "completed":true,
      //     "files":[
  
      //     ]
      // },
      // "2":{
      //     "completed":true,
      //     "files":[
  
      //     ]
      // },
      // "3":{
      //     "completed":true,
      //     "files":[
      //         {
      //             "id":155912339958110,
      //             "section":2,
      //             "uri":"http://39.98.57.36:8080/easy_to_adopt_app_backend/appCollectionFile/2,ca2e79ff04ac?width=400&height=800&mode=fit"
      //         },
      //         {
      //             "id":155912339958211,
      //             "section":2,
      //             "uri":"http://39.98.57.36:8080/easy_to_adopt_app_backend/appCollectionFile/1,ca30377eee71?width=400&height=800&mode=fit"
      //         },
      //         {
      //             "id":155912339958212,
      //             "section":2,
      //             "uri":"http://39.98.57.36:8080/easy_to_adopt_app_backend/appCollectionFile/4,ca3129afa950?width=400&height=800&mode=fit"
      //         },
      //         {
      //             "id":155912339958213,
      //             "section":2,
      //             "uri":"http://39.98.57.36:8080/easy_to_adopt_app_backend/appCollectionFile/2,ca32c61d89a1?width=400&height=800&mode=fit"
      //         },
      //         {
      //             "id":155912339958314,
      //             "section":2,
      //             "uri":"http://39.98.57.36:8080/easy_to_adopt_app_backend/appCollectionFile/3,ca34fcef4403?width=400&height=800&mode=fit"
      //         }
      //     ]
      // },
      // "4":{
      //     "completed":true,
      //     "files":[
  
      //     ]
      // },
      // "5":{
      //     "completed":true,
      //     "files":[
  
      //     ]
      // },
      // "tags":{
      //     "8":false,
      //     "9":false,
      //     "10":false
      // },
      // "memo":"",
      // "isAllComplete":true
  })
    finalData.matter = JSON.stringify(matter);
    selectedRowKeysClient.map(item => {
      party.push({ partyKey: item.idCard, partyType: '0' })
      partyName.push(item.name)
      partyMobile.push(item.mobile)
    });
    // console.log(selectedRowKeysClient)
    // console.log(selectedRowKeysORG)
    selectedRowKeysORG.map(item => {
      party.push({ partyKey: item.creditCode, partyType: '1' })
      partyName.push(item.name)
      partyMobile.push(item.mobile)
    });
    let partyNameJoin = partyName.join();
    let partyMobilejoin = partyMobile.join();
    if (party.length == 0) {
      message.error("请至少选择一个当事人")
      return
    }
    finalData.partyName = partyNameJoin
    finalData.partyMobile = partyMobilejoin
    console.log(party, 'party')
    finalData.party = JSON.stringify(party);
    const costInfo = {};
    Object.keys(matterOtherData).map(key => {
      const item = matterOtherData[key];
      if (item['cost'] != undefined) {
        costInfo[key] = item['cost'];
      }
    });
    if (matterOtherData.approvalLevel == undefined) {
      message.error("未完善审批信息,本批次不能保存!")
      return
    }
    finalData.approvalLevel = matterOtherData.approvalLevel;
    finalData.payState = matterOtherData['feeChecked'] || 0;
    finalData.costInfo = JSON.stringify(costInfo);
    finalData.clientUpdateAt = timestamp
    console.log(finalData,'finalData')
    saveDataToIndex(finalData);
    // goBackToIndex();
  };
  const saveMatterData = () => {
    const editIndex = sessionStorage.getItem("editIndex")
    let newIndex = matterIndex + 1;
    let idCards = [];
    let creditCodes = [];
    let matterItem = {};
    let partyNamesArry = [];
    partyList.map(item => {
      if (item.partyType == '0') {
        idCards.push(item.id);
      } else {
        creditCodes.push(item.id)
      }
      partyNamesArry.push(item.name);
    });
    let idCardsJoin = idCards.join();
    let newVideo = []
    vedioList.map((item) => {
      newVideo.push(encodeURIComponent(item))
    })
    let vedioJoin = newVideo.join();
    if (idCards.length === 0 && creditCodes.length === 0) {
      message.error("请至少选择一个当事人")
      return
    }
    let partyNames = partyNamesArry.join();
    let creditCodesJoin = creditCodes.join();
    const matterId = sessionStorage.getItem('matterId');
    const matterData = matterOtherData[matterId];
    matterItem.supplementState = supplementState;
    matterItem.batchId =parseInt(sessionStorage.getItem("batchId"));
    matterItem.id = parseInt(matterId);
    matterItem.video = vedioJoin;
    matterItem.translation = translation|| '';
    matterItem.currency = currency||'';
    matterItem.number = parseInt(number) || 1;
    matterItem.translation = translation || '';
    matterItem.currency = currency || '';
    matterItem.idCard = idCardsJoin;
    matterItem.creditCode = creditCodesJoin;
    if (editIndex != -1) {
      matterItem.index = parseInt(editIndex) + 1;
    } else {
      matterItem.index = matter.length + 1;
    }
    if (typeof name != 'string') {
      matterItem.name = name[name.length-1];
    } else {
      matterItem.name = name
    }
    matterItem.partyName = partyNames;
    if (matterData && matterData['memoText']) {
      matterItem.memo = matterData['memoText'];
    }
    if (matterData && matterData['tags']) {
      matterItem.tags = matterData['tags']
    }
   
    matterItem.files = fileList
    if (editIndex != -1) {
      matter.splice(editIndex, 1, matterItem)
    } else {
      matter.push(matterItem);
    }
    console.log(matter, 'matter')
    saveMatterDataToIndex(matter, newIndex);
  };

  const choiceClient = () => {
    choiceClientFuction();
  };
  const choiceMatter = () => {
    choiceMatterFuction();
  };
  const matterContentProps = {
    isEditMatter, isEditBatch,
    goToNewMatterView,dispatch,
    matter,
    deleteMatterItemToClientAndMatter(matter) {
      deleteMatterItemToClientAndMatters(matter);
    },
    toEditMatter(index, row) {
      editMatterToClientAndMatters(index, row);
    }
  };
  const NewMatterProps = {
    fileList, isEditMatter, memoText, infoId, supplementState, currentFile, vedioList,
    showCascader,
    getTagList, memoList,
    partyList,
    PartyClientKeysCancle,
    PartyORGKeysCancle,
    selectedRowKeysClient,
    selectedRowKeysORG,
    showAddView,
    PartyClientKeys,
    PartyClientList,
    PartyORGKeys,
    PartyORGList,
    name,
    matterId,
    number,
    onInfoChecked(value) {
      infoChecked = value;
    },
    toShowAddView(visible) {
      toShowAddViews(visible);
    },
    getPartyClientArry(PartyClientKeys, PartyClientList) {
      getPartyClientArrys(PartyClientKeys, PartyClientList);
    },
    getPartyORGArry(PartyORGKeys, PartyORGList) {
      getPartyORGArrys(PartyORGKeys, PartyORGList);
    },
    confirmToClientAndmatterName(partyList, PartyClientKeys, PartyORGKeys) {
      confirmToClientAndmatterNames(partyList, PartyClientKeys, PartyORGKeys);
    },
    choiceMatterToclientAndMatterView(name) {
      choiceMatterToclientAndMatterViews(name);
    },
    getCopies(number) {
      getCopiesToindex(number);
    },
    heelPartyList(partyList) {
      heelPartyLists(partyList);
    },
    getVedioList(currentArry) {
      getVedioLists(currentArry)
    },
    getFileList(file) {
      getFileLists(file)
    },
    changeSupplementState(SupplementState) {
      changeSupplementStates(SupplementState)
    }
  };
  const clientContentProps = {
    isEditMatter,
    clientList,
    paginationClientList,
    selectedRowKeysClient,
    paginationMatter,
    clientRowKeys,
    ORGRows,
    orgListData,
    selectedRowKeysORG,
    onChangeClientLsits(page) {
      onChangeClientLsit(page);
    },
    onChangeMatterPage(page) {
      onChangeMatterPages(page);
    },
    getClientCurrentList(selectedRowKeysClient, clientRowKeys) {
      getClientCurrentLists(selectedRowKeysClient, clientRowKeys);
    },
    getORGCurrentList(ORGCurrentList, ORGRows) {
      getORGCurrentLists(ORGCurrentList, ORGRows);
    },
  };
  return (
    <div style={{ flex: 1, backgroundColor: '#F8F8F8', flexDirection: 'column' }}>
      {/* 头部 */}
      <div
        style={{
          padding: 20,
          borderBottom: '1px solid #f0f0f0',
          overflow: 'hidden',
          backgroundColor: 'white',
        }}
      >
        <Button
          style={{ fontSize: 14, float: 'left', border: 0, paddingLeft: 0 }}
          onClick={showFinalMatter ? goToclientAndMatterView : goToBack}
        >
          <Icon type="left" />
          <span>返回</span>
        </Button>
        <div style={{ float: 'right' }}>
          <Button
            className="margin-right"
            onClick={showFinalMatter ? reserMatter : reSetAddParTyData}
          >
            重置
          </Button>
          <Button type="primary" onClick={showFinalMatter ? saveMatterData : saveData}>
            保存
          </Button>
        </div>
      </div>
      {/* tabs */}
      {showFinalMatter ? (
        <NewMatter {...NewMatterProps} />
      ) : (
          <div style={{ backgroundColor: 'white' }}>
            <ul style={{ width: 280, margin: '0 auto', overflow: 'hidden' }}>
              <li style={{ float: 'left', width: '50%' }}>
                <a
                  style={{
                    textAlign: 'center',
                    display: 'inline-block',
                    padding: '25px 0',
                    margin: '0 20px',
                    fontSize: 16,
                    color: showClient ? '#1890FF' : '#333',
                    borderBottom: showClient ? '2px solid #1890FF' : '2px solid transparent'
                  }}
                  onClick={choiceClient}
                >
                  当事人列表
              </a>
              </li>
              <li style={{ float: 'left', width: '50%' }}>
                <a
                  style={{
                    textAlign: 'center',
                    display: 'inline-block',
                    padding: '25px 0',
                    margin: '0 20px',
                    fontSize: 16,
                    color: !showClient ? '#1890FF' : '#333',
                    borderBottom: !showClient ? '2px solid #1890FF' : '2px solid transparent'
                  }}
                  onClick={choiceMatter}
                >
                  选择事项
              </a>
              </li>
            </ul>
          </div>
        )}
      {/* 内容 */}
      {showFinalMatter ? null : showClient ? (
        <ClientContent {...clientContentProps} />
      ) : (
          <MatterContent {...matterContentProps} />
        )}
    </div>
  );
};

export default ClientAndMattersName;
